import { sp } from "cc";
import { Loger } from "../loger/Loger";
import { ResUtils } from './ResUtils';

export class SpineUtils {

    public static loadSpine(path:string) : Promise<sp.SkeletonData>{
        return ResUtils.loadRes<sp.SkeletonData>(path)
    }

    public static loadSpineArray(pathArray:string[]): Promise<sp.SkeletonData[]>{
        return ResUtils.loadResArray<sp.SkeletonData>(pathArray);
    }

    /**导出时在同一个插槽上，挂多个附件，根据名字替换当前显示的附件 */
    public static changeCloth(skeleton:sp.Skeleton, slotName:string, targetSkinName:string, targetAttaName:string){
        Loger.log('change cloth:', slotName, targetSkinName, targetAttaName);
        const slot = skeleton.findSlot(slotName);
        const skeletonData = skeleton.skeletonData.getRuntimeData();
        const skin = skeletonData.findSkin(targetSkinName);
        const slotIndex = skeletonData.findSlotIndex(slotName);
        const atta = skin.getAttachment(slotIndex, targetAttaName);;
        slot.setAttachment(atta);
    }

    public static changeAnimation(skeleton:sp.Skeleton, animName:string) {
        skeleton.setAnimation(0,animName,true)
    }

    public static setSpineData(skeleton:sp.Skeleton,data:sp.SkeletonData,animName:string = null,skin:string = null){
        skeleton.skeletonData = data
        if (animName) {
            skeleton.setAnimation(0,animName,true)
        }
        if (skin) {
            skeleton.setSkin(skin)
        }
    }

    /**播放动画,播放完成异步回调 */
    static playSpineAnimation(spine: sp.Skeleton, animName: string, loop: boolean): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            if (!spine) {
                resolve();
                return;
            }
            if (spine.animation == animName) {
                resolve();
                return;
            }

            let track = spine.setAnimation(0, animName, loop);
            if (track) {
                // 注册动画的结束回调
                spine.setCompleteListener((trackEntry) => {
                    let name = trackEntry.animation ? trackEntry.animation.name : '';
                    if (name === animName) {
                        resolve(); // 动画结束后执行自己的逻辑
                        return;
                    }
                });
            } else {
                resolve();
                return;
            }
        })

    }
    
}